package com.bkgy.jobs;

import com.bkgy.controller.qualityDaily.service.IQualitydailyMainDataService;
import com.bkgy.controller.qualityDaily.service.IQualitydailyMaterialRepService;
import com.bkgy.controller.repOutput.entity.RepOutput;
import com.bkgy.controller.repOutput.service.IRepOutputService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

/**
 * 1.在对应时间点更新班产、日产、月产、年产 REP_OUTPUT
 * 2.更新质量报表》主体指标完成情况 结果存入表 QUALITYDAILY_MAIN_DATA
 * 3.更新质量日报》原料质量影响，结果存表 QUALITYDAILY_MATERIAL_REP
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class HourTaskJob {
    private final IQualitydailyMainDataService plankservice;
    private final IRepOutputService repOutputService;
    private final IQualitydailyMaterialRepService materRepService;
    public static int oldMonth, oldYear;

    public void exec() {
        //任务1：作业区总览》产量记录，更新班产、日产、月产、年产
        try {
            updateOutputRep();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }

        //任务2：更新质量日报》主体指标完成情况
        try {
            plankservice.buildData(new Date());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }

        //任务3：更新质量日报》原料质量影响
        try {
            materRepService.buildMaterialRepJob(new Date());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 根据不同时间点，将班产、日产、月产、年产置为0
     */
    private void updateOutputRep() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());

        int hour = cal.get(Calendar.HOUR_OF_DAY);
        RepOutput rep = new RepOutput();
        boolean flag = false;
        if (hour == 8 || hour == 19) {
            //8点、19点重置班产量置为0
            rep.setBanchan(BigDecimal.ZERO);
            flag = true;
        } else if (hour == 0) {
            //0点更新日产量
            rep.setRichan(BigDecimal.ZERO);
            flag = true;
        }

        //跨月，将月累计产量归零
        int month = cal.get(Calendar.MONTH);
        if (month != oldMonth) {
            rep.setYuechan(BigDecimal.ZERO);
            flag = true;
        }

        //跨年，将年累计产量归零
        int year = cal.get(Calendar.YEAR);
        if (year != oldYear) {
            rep.setNianchan(BigDecimal.ZERO);
            flag = true;
        }

        if (flag) {
            String[] lineList = new String[]{"tcm2280", "cal2150", "cal1630", "cgl1870", "prod"};
            for (String lineName : lineList) {
                rep.setLineName(lineName);
                repOutputService.updateById(rep);
            }
        }
    }
}
